package setting

import (
	"../common"
	"../web"
	"encoding/json"
	"strconv"
	"strings"
)

type SetItemObj struct {
	common.BaseHandler
}

type ItemQueryPageObj struct {
	common.BaseHandler
}

func (self *SetItemObj) Prepare() {
	routings := *common.FetchAllRowsPtr(
		`SELECT DISTINCT NAME 
           FROM SFC_ROUTING(NOLOCK) 
          ORDER BY NAME`,
		self.Usr.Conn, new(common.RouteName))

	facs := *common.FetchAllRowsPtr(
		`SELECT FACTORYCODE 
           FROM SFC_FACTORY(NOLOCK) 
          ORDER BY FACTORYCODE`,
		self.Usr.Conn, new(common.Factory))

	items := *common.FetchAllRowsPtr(
		`SELECT TOP 10 ROW_NUMBER() OVER(ORDER BY ITEM),ITEM,ISNULL(DESCRIP,''),
                 ISNULL(FREQUENCYS,''),ISNULL(LIMIT,''),ISNULL(ROUTING,''),ISNULL(PRODTYPE,''),
                 ISNULL(PRODCODE,''),ISNULL(FACTORYCODE,''),PACKQTY,
                 CASE LOCKED WHEN 1 THEN 'Y' ELSE 'N' END 
           FROM SFC_ITEMS(NOLOCK)`,
		self.Usr.Conn, new(common.ItemDefine))

	band := *common.FetchAllRowsPtr(
		`SELECT FREQUENCY
           FROM SFC_FREQUENCY(NOLOCK)
          ORDER BY IDX`,
		self.Usr.Conn, new(common.RecDataStr))

	curr_id := 1
	iRtnData := *common.FetchOneRowPtr(
		`SELECT COUNT(ITEM)
           FROM SFC_ITEMS(NOLOCK)`,
		self.Usr.Conn, new(common.RecCount))
	recnum := iRtnData.(common.RecCount).Number
	total_id := recnum / 10
	if recnum%10 > 0 {
		total_id = total_id + 1
	}

	self.TmplData["routings"] = routings
	self.TmplData["facs"] = facs
	self.TmplData["items"] = items
	self.TmplData["curr_page"] = curr_id
	self.TmplData["total_page"] = total_id
	self.TmplData["band"] = band
}

func (self *SetItemObj) ParameterCheck() bool {
	c_item := strings.TrimSpace(self.Ctx.Params["item"])
	c_type := strings.TrimSpace(self.Usr.Prod)
	c_prod := strings.TrimSpace(self.Ctx.Params["prodcode"])
	c_fact := self.Ctx.Params["factory"]
	c_desc := strings.TrimSpace(self.Ctx.Params["descrip"])
	c_rout := self.Ctx.Params["rout"]
	c_limt := strings.TrimSpace(self.Ctx.Params["limit"])
	c_pckq := strings.TrimSpace(self.Ctx.Params["packqty"])
	c_band := ""
	band := self.TmplData["band"].([]interface{})
	for _, bd := range band {
		bdval := bd.(common.RecDataStr).Data
		chkbd := self.Ctx.Params[bdval]
		if chkbd == "1" {
			if c_band == "" {
				c_band = bdval
			} else {
				c_band = c_band + "," + bdval
			}
		}
	}
	if c_item == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the item number.")
		return false
	}
	/*
		if c_type == "" {
			self.TmplData["error"] = common.GetText(self.Lang, "Please select the product type.")
			return false
		}
		if c_fact == "" {
			self.TmplData["error"] = common.GetText(self.Lang, "Please input the factory code.")
			return false
		}
	*/
	if c_band == "" && c_limt != "" {
		c_limt = ""
	}
	if c_band != "" && c_limt == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Limit value.")
		return false
	}
	_, err := strconv.Atoi(c_pckq)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Pack Qty must be a numberic.")
		return false
	}
	/*
		if c_limt != "" {
			val := strings.Split(c_limt, ",")
			if len(val) == 1 {
				_, err := strconv.ParseFloat(strings.TrimSpace(c_limt), 32)
				if err != nil {
					self.TmplData["error"] = common.GetText(self.Lang, "Limit value must be a numberic.")
					return false
				}
			} else {
				for i, local := range val {
					_, err := strconv.ParseFloat(strings.TrimSpace(local), 32)
					if err != nil {
						self.TmplData["error"] = common.GetText(self.Lang,
							"Index %d Limit: %s must be a numberic.", i, local)
						return false
					}
				}
			}
		}
	*/

	self.Sqlparas = append(self.Sqlparas, c_item)
	self.Sqlparas = append(self.Sqlparas, c_type)
	self.Sqlparas = append(self.Sqlparas, c_prod)
	self.Sqlparas = append(self.Sqlparas, c_fact)
	self.Sqlparas = append(self.Sqlparas, c_desc)
	self.Sqlparas = append(self.Sqlparas, c_rout)
	self.Sqlparas = append(self.Sqlparas, c_band)
	self.Sqlparas = append(self.Sqlparas, c_limt)
	self.Sqlparas = append(self.Sqlparas, c_pckq)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{strings.ToUpper(c_item)}

	return true
}

func (self *SetItemObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetItems ?, ?, ?, ?, ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func ItemSetHandler(ctx *web.Context) {
	self := new(SetItemObj)
	self.Ctx = ctx
	self.Url = "/setitem"
	self.Html = "setitem.html"
	self.Rightlist = []string{"setitem"}
	self.Flashstr = "Set Item: [ %v ] finished."
	self.Do(self)
}

func (self *ItemQueryPageObj) ParameterCheck() bool {
	s_page := self.Ctx.Params["pageid"]
	pageid, err := strconv.Atoi(s_page)
	if err != nil {
		return false
	}

	idx := 10 * (pageid - 1)
	self.Sqlparas = append(self.Sqlparas, idx)

	return true
}

func (self *ItemQueryPageObj) SqlQueryExecute() {
	items := *common.FetchAllRowsPtr(
		`SELECT TOP 10 A.AUTOID, A.ITEM, A.DESCRIP, A.FREQUENCYS, A.LIMIT, A.ROUTING, 
				 A.PRODTYPE, A.PRODCODE, A.FACTORYCODE, A.PACKQTY, A.LOCKED
           FROM
                (
					SELECT ROW_NUMBER() OVER(ORDER BY ITEM) AS AUTOID,ITEM,
							ISNULL(DESCRIP,'') AS DESCRIP, ISNULL(FREQUENCYS,'') AS FREQUENCYS, 
							ISNULL(LIMIT,'') AS LIMIT, ISNULL(ROUTING,'') AS ROUTING, ISNULL(PRODTYPE,'') AS PRODTYPE, 
							ISNULL(PRODCODE,'') AS PRODCODE, ISNULL(FACTORYCODE,'') AS FACTORYCODE,PACKQTY,
			                CASE LOCKED WHEN 1 THEN 'Y' ELSE 'N' END AS LOCKED
			          FROM SFC_ITEMS(NOLOCK)
			    ) A
		  WHERE A.AUTOID > ?`,
		self.Usr.Conn, new(common.ItemDefine), self.Sqlparas...)

	dict_js, _ := json.Marshal(map[string]interface{}{"items": items, "lang": self.Lang})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func ItemSetPageHandler(ctx *web.Context) {
	self := new(ItemQueryPageObj)
	self.Ctx = ctx
	self.DoJsonQuery(self)
}
